package com.code2roc.fastboot.system.setting.controller;

import com.code2roc.fastboot.system.setting.bizlogic.GroupLogic;
import com.code2roc.fastboot.system.setting.model.SystemGroupDO;
import com.code2roc.fastboot.system.setting.service.ISystemGroupService;
import com.code2roc.fastboot.system.enums.CommonEnum;
import com.code2roc.fastboot.model.BaseBootController;
import com.code2roc.fastboot.util.ZTreeBuilder;
import com.code2roc.fastboot.model.ZTreeNode;
import com.code2roc.fastboot.framework.extra.formupdate.UpdateRequestBody;
import com.code2roc.fastboot.framework.model.Result;
import com.code2roc.fastboot.framework.util.ConvertOp;
import com.code2roc.fastboot.framework.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/setting/group")
public class SystemGroupController extends BaseBootController {
    @Autowired
    private ISystemGroupService service;
    @Autowired
    private GroupLogic groupLogic;


    @ResponseBody
    @PostMapping("/tree")
    public Object tree(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String parentGroupTag = ConvertOp.convert2String(params.get("groupTag"));
        List<SystemGroupDO> entityList =  service.selectAllList();
        List<ZTreeNode> treeNodeList = new ArrayList<ZTreeNode>();
        if(!StringUtil.isEmpty(parentGroupTag)){
            for (SystemGroupDO entity:entityList) {
                ZTreeNode tree = new ZTreeNode();
                tree.setId(entity.getRow_id());
                tree.setpId(entity.getParent_id());
                tree.setName(entity.getGroup_name());
                tree.setSotNum(entity.getSort_num());
                if(entity.getGroup_tag().equals(parentGroupTag)){
                    tree.setTopNode(true);
                    tree.setOpen(true);
                }
                tree.addAttribute("groupTag",entity.getGroup_tag());
                treeNodeList.add(tree);
            }
        }else{
            ZTreeNode rootNode = new ZTreeNode();
            rootNode.setId("Top");
            rootNode.setpId("-1");
            rootNode.setName("根");
            rootNode.setOpen(true);
            rootNode.setTopNode(true);
            rootNode.setNocheck(true);
            treeNodeList.add(rootNode);
            for (SystemGroupDO entity:entityList) {
                ZTreeNode tree = new ZTreeNode();
                tree.setId(entity.getRow_id());
                tree.setpId(entity.getParent_id());
                tree.setName(entity.getGroup_name());
                tree.setSotNum(entity.getSort_num());
                tree.setTopNode(false);
                tree.addAttribute("groupTag",entity.getGroup_tag());
                treeNodeList.add(tree);
            }
        }
        List<ZTreeNode> obj = ZTreeBuilder.BuildTree(treeNodeList);
        return result.add("obj",obj);
    }

    @ResponseBody
    @PostMapping("/list")
    public Object list(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String sql = "1=1";
        HashMap<String, Object> paramMap = new HashMap<>();
        String group_name = ConvertOp.convert2String(params.get("group_name"));
        String parent_id = ConvertOp.convert2String(params.get("parent_id"));
        if(parent_id.equals("Top")){
            if (!StringUtil.isEmpty(group_name)) {
                sql += " and group_name like #{group_name}";
                paramMap.put("group_name", "%" + group_name + "%");
            }
        }else{
            String guidString = "";
            List<String> guidList = service.getAllSubGroupIDList(parent_id).stream().distinct().collect(Collectors.toList());
            if (guidList.size() == 0) {
                guidString = "''";
            } else {
                for (int i = 0 ; i < guidList.size(); i++) {
                    if(i==guidList.size()-1){
                        guidString += "'"+guidList.get(i)+"'";
                    }else{
                        guidString += "'"+guidList.get(i)+"',";
                    }
                }
            }
            sql += " and row_id in ("+guidString+")";

            if (!StringUtil.isEmpty(group_name)) {
                sql += " and group_name like #{group_name}";
                paramMap.put("group_name", "%" + group_name + "%");
            }
        }

        List<SystemGroupDO> rows = service.selectPageList("*", sql, "sort_num desc", paramMap);
        int total = service.selectCount(sql, paramMap);
        result.add("rows", rows);
        result.add("total", total);
        return result;
    }

    @ResponseBody
    @PostMapping("/insert")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object insert(@RequestBody SystemGroupDO entity) {
        Result result = Result.okResult();
        if(service.checkExist("group_tag",entity.getGroup_tag())){
            return Result.errorResult().setMsg("目录标识已存在");
        }
        service.insert(entity);
        return result;
    }

    @ResponseBody
    @PostMapping("/detail")
    public Object detail(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String row_id = ConvertOp.convert2String(params.get("row_id"));
        result.add("obj", service.selectOne(row_id));
        return result;
    }

    @ResponseBody
    @PostMapping("/update")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object update(@UpdateRequestBody SystemGroupDO entity) {
        Result result = Result.okResult();
        if(service.checkExist("group_tag",entity.getGroup_tag(),entity.getRow_id())){
            return Result.errorResult().setMsg("目录标识已存在");
        }
        service.update(entity);
        return result;
    }

    @ResponseBody
    @PostMapping("/batchUpdate")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object batchUpdate(@UpdateRequestBody List<SystemGroupDO> entityList) {
        Result result = Result.okResult();
        service.batchUpdate(entityList);
        return result;
    }

    @ResponseBody
    @PostMapping("/delete")
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_UNCOMMITTED)
    public Object delete(@RequestBody Map<String, Object> params) {
        Result result = Result.okResult();
        String row_id = ConvertOp.convert2String(params.get("row_id"));
        SystemGroupDO entity = service.selectOne(row_id);
        if(entity.getSystem_init()== CommonEnum.YesOrNo.Yes.get_value()){
            return Result.errorResult().setMsg("系统内置数据，禁止删除");
        }
        if(service.checkExistSub(row_id)){
            return Result.errorResult().setMsg("存在子类目录");
        }
        service.delete(row_id);
        return result;
    }

    @ResponseBody
    @PostMapping("/exportData")
    public Object exportData(@RequestBody Map<String, Object> params) throws Exception {
        Result result = Result.okResult();
        String fileid = groupLogic.exportData();
        result.add("fileid", fileid);
        return result;
    }

    @ResponseBody
    @PostMapping("/importData")
    public Object importData(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        Result result = Result.okResult();
        String errormsg = groupLogic.importData(file.getInputStream());
        if (!StringUtil.isEmpty(errormsg)) {
            return Result.errorResult().setMsg(errormsg);
        }
        return result;
    }

}
